<script>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import {onBeforeUnmount, ref, shallowRef, watch} from "vue";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";

const imgUrl = import.meta.env.VITE_BASE_API + "/business_account/business_upload_image";
export default {
  components: {Editor, Toolbar},
  props: {
    modelValue: {type: String, default: ""},
  },
  emits: ["update:modelValue"],
  setup(prop, {emit}) {
    
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    
    // 内容 HTML
    const valueHtml = ref();
    // 模拟 ajax 异步获取内容
    const toolbarConfig = {
      // 删除对应的 toolbar 功能
      excludeKeys: [
        'insertVideo', 'uploadVideo', 'editVideoSize'
      ]
    };
    const editorConfig = ref({
      placeholder: "请输入内容...",
      MENU_CONF: {
        uploadImage: {
          server: imgUrl,
          allowedFileTypes: ["image/*"],
          fieldName: "file",
          customInsert(res, insertFn) {
            const url = res.data;
            insertFn(url, "", url);
          },
        },
      },
    });
    
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });
    
    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };
    watch(
      () => valueHtml.value,
      (newVal) => {
        emit("update:modelValue", newVal);
      }
    );
    watch(
      () => prop.modelValue,
      (newVal) => {
        /**
         * 富文本编辑器，如果内容为 <p><br></p> 等于空.
         * 需要设置 modelValue 为空，否则表单校验会异常.
         */
        if(newVal == "<p><br></p>"){
          valueHtml.value = "";
        }else {
          valueHtml.value = newVal;
        }
      },
      {immediate: true}
    );
    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
    };
  },
};
</script>
<template>
  <div style="border: 1px solid #ccc;" class="w-full">
    <!-- <div style="padding: 5px">视频上传无法展示，请勿上传视频</div> -->
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
    />
  </div>
</template>
